/**
 * 使用react-intl-universal进行语言切换
 * 会刷新页面
 */
import React, { useState, useEffect } from 'react'
import intl from 'react-intl-universal';
import US from './en-US'
import CN from './zh-CN'
import { getState, setState } from '@/common/state'
import { Select } from 'antd'
const { Option } = Select;
const key = 'language'
const locales = {
    "en-US": US,
    "zh-CN": CN,
    "en_d": require('./en_d.json')
};
export const SUPPOER_LOCALES = [
    {
        name: 'English',
        value: 'en-US'
    },
    {
        name: '简体中文',
        value: 'zh-CN'
    },
    {
        name: '默认',
        value: 'en_d'
    }
];

let set = {}

/**
 * 语言切换组件
 * @returns 
 */
export function LanguageSelect({ width = 120 } = {}) {
    const options = SUPPOER_LOCALES.map(({ name, value }) => <Option key={value} value={value}>{name}</Option>)
    const handleChange = value => {
        setState(key, value)
        set.setLoca(false)
        set.setLang(value)
    };
    return (<Select defaultValue={getState(key)} style={{ width }} onChange={handleChange}>
        {options}
    </Select>)
}

/**
 * 文本
 * @param {*} props 
 * @returns 
 */
export function Lang(props = {}) { 
    const { str, d = '', params = {} } = props
    return (<>{intl.get(str, params).d(d)}</>)
}

/**
 * 使用hooks实现语言切换
 */
export function useLanguage() {
    const [, setLoca] = useState(false)
    const [lang, setLang] = useState(getState(key))
    set = { setLoca, setLang }
    useEffect(() => {
        let currentLocale = lang
        intl.init({ currentLocale, locales }).then(() => {
            setLoca(true)
            setLang(lang)
        })
    }, [lang])
}
